<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gongxicheng.cn","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="指令最常见的一个应用是创建可重用构件。 下面的为代码展示了一个简单版本的对话框指令的使用。 12345678910&lt;div&gt;  &lt;button ng-click&#x3D;&quot;show&#x3D;true&quot;&gt;show&lt;&#x2F;button&gt;   &lt;dialog title&#x3D;&quot;Hello .&quot;          visible&#x3D;&quot;show&quot;          on-cancel&#x3D;&quot;sh">
<meta property="og:type" content="article">
<meta property="og:title" content="作用域与Transcluded指令是如何工作的">
<meta property="og:url" content="gongxicheng.cn/2020/02/16/2020/2020-02-16-%E4%BD%9C%E7%94%A8%E5%9F%9F%E4%B8%8ETranscluded%E6%8C%87%E4%BB%A4%E6%98%AF%E5%A6%82%E4%BD%95%E5%B7%A5%E4%BD%9C%E7%9A%84/index.html">
<meta property="og:site_name" content="恭喜">
<meta property="og:description" content="指令最常见的一个应用是创建可重用构件。 下面的为代码展示了一个简单版本的对话框指令的使用。 12345678910&lt;div&gt;  &lt;button ng-click&#x3D;&quot;show&#x3D;true&quot;&gt;show&lt;&#x2F;button&gt;   &lt;dialog title&#x3D;&quot;Hello .&quot;          visible&#x3D;&quot;show&quot;          on-cancel&#x3D;&quot;sh">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-02-16T10:34:05.000Z">
<meta property="article:modified_time" content="2020-12-03T05:23:42.441Z">
<meta property="article:author" content="Gary Gong">
<meta property="article:tag" content="angularjs">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="gongxicheng.cn/2020/02/16/2020/2020-02-16-%E4%BD%9C%E7%94%A8%E5%9F%9F%E4%B8%8ETranscluded%E6%8C%87%E4%BB%A4%E6%98%AF%E5%A6%82%E4%BD%95%E5%B7%A5%E4%BD%9C%E7%9A%84/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>作用域与Transcluded指令是如何工作的 | 恭喜</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-123017381-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-123017381-1');
      }
    </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">恭喜</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="gongxicheng.cn/2020/02/16/2020/2020-02-16-%E4%BD%9C%E7%94%A8%E5%9F%9F%E4%B8%8ETranscluded%E6%8C%87%E4%BB%A4%E6%98%AF%E5%A6%82%E4%BD%95%E5%B7%A5%E4%BD%9C%E7%9A%84/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Gary Gong">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="恭喜">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          作用域与Transcluded指令是如何工作的
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-02-16 10:34:05" itemprop="dateCreated datePublished" datetime="2020-02-16T10:34:05+00:00">2020-02-16</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-12-03 05:23:42" itemprop="dateModified" datetime="2020-12-03T05:23:42+00:00">2020-12-03</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>指令最常见的一个应用是创建可重用构件。</p>
<p>下面的为代码展示了一个简单版本的对话框指令的使用。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">button</span> <span class="attr">ng-click</span>=<span class="string">"show=true"</span>&gt;</span>show<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"> </span><br><span class="line">  <span class="tag">&lt;<span class="name">dialog</span> <span class="attr">title</span>=<span class="string">"Hello ."</span></span></span><br><span class="line"><span class="tag">          <span class="attr">visible</span>=<span class="string">"show"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">on-cancel</span>=<span class="string">"show = false"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">on-ok</span>=<span class="string">"show = false; doSomething()"</span>&gt;</span></span><br><span class="line">     Body goes here:  is .</span><br><span class="line">  <span class="tag">&lt;/<span class="name">dialog</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>点击 “show” 按钮会打开对话框。对话框会有一个和 username 绑定的标题，同时会有一个主体，这个主体我们是通过在对话框指令定义中的模板通过 transclude 插入的。</p>
<p>下面是 dialog 指令中的模板属性：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-show</span>=<span class="string">"visible"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">h3</span>&gt;</span><span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"body"</span> <span class="attr">ng-transclude</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"footer"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">ng-click</span>=<span class="string">"onOk()"</span>&gt;</span>Save changes<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">ng-click</span>=<span class="string">"onCancel()"</span>&gt;</span>Close<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>上面这个指令的模板还不能适当地渲染，除非我们施上一些魔法。</p>
<p>第一个问题是解决对话框模板中需要的 title 数据。而我们希望模板中的 title 和指令 <dialog> 被使用时的 title 属性一致（也就是 “Hello “）。而且，模板中的按钮会去调用作用域中的 onOk 和 onCancel 两个函数，而这两个函数的来源也在指令的属性中有定义，要解决的就是映射的问题了。为了解决这个映射问题，我们使用本地 scope 创建本地变量（模板中需要的数据和函数）和外部变量（指令中已有的属性）映射：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">scope: &#123;</span><br><span class="line">  title: <span class="string">'@'</span>,             <span class="comment">// the title uses the data-binding from the parent scope</span></span><br><span class="line">  onOk: <span class="string">'&amp;'</span>,              <span class="comment">// create a delegate onOk function</span></span><br><span class="line">  onCancel: <span class="string">'&amp;'</span>,          <span class="comment">// create a delegate onCancel function</span></span><br><span class="line">  visible: <span class="string">'='</span>            <span class="comment">// set up visible to accept data-binding</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在指令的作用域创建本地变量会产生两个问题：</p>
<p>独立的作用域 - 如果用户（译注：使用对话框指令的开发者）在使用 dialog 指令时忘记设置 title 属性，那么对话框指令的模板中的 title 解析时则会去绑定父级作用域中的同名属性。这是完全不可预测的，也不是我们希望看到的。</p>
<p>transclusion - 通过引用包含的DOM节点可以看到指令的本地变量，而这本地变量有可能会重写掉一些 transclusion （引用包含）中数据绑定的同名属性。在上述例子中，比如像指令所在的 scope 中的 title 属性就重写了在 transclusion （引用包含）的作用域的 title 属性（译注：这里 Body goes here:  is 作用域与Transcluded指令是如何工作的. 是通过 transclusion 插入到 dialog 指令模版中拥有 ng-transclude 属性的div中，这样它里面的 title 插值就会被 dialog 本地的 title 值改写 ）</p>
<p>为了解决缺少隔离的问题，指令会声明一个 isolated 作用域。一个隔离的作用域不会通过基于原型的方式继承它的父级作用域，所以我嗯就不用担心会有属性被意外改写的情况了。</p>
<p>但是，独立的作用域引来了另外一个问题：如果一个 transcluded（引用包含的） DOM节点是一个指令独立作用域的孩子节点的话，那么它不会绑定到任何数据（译注：像我们上面例子中的情况，就属于绑定不到数据）。出于此，在指令为本地变量创建出独立的作用域之前，我们需要声明 transcluded（引用包含的）作用域是原始作用域（也是独立作用域的父级）的孩子。这样，引用包含创建的作用域就和独立作用域拥有同样的父级，也就是说它们是兄弟作用域。</p>
<p>这会让一切看起来意想不到的复杂，但至少它让指令（控件）的用户和开发者不会那么难以接受。</p>
<p>因此，我们上面例子中指令作用域的声明，最后开起来是这样子的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">transclude: <span class="literal">true</span>,</span><br><span class="line">scope: &#123;</span><br><span class="line">    title: <span class="string">'@'</span>,             <span class="comment">// the title uses the data-binding from the parent scope</span></span><br><span class="line">    onOk: <span class="string">'&amp;'</span>,              <span class="comment">// create a delegate onOk function</span></span><br><span class="line">    onCancel: <span class="string">'&amp;'</span>,          <span class="comment">// create a delegate onCancel function</span></span><br><span class="line">    visible: <span class="string">'='</span>            <span class="comment">// set up visible to accept data-binding</span></span><br><span class="line">&#125;,</span><br><span class="line">restrict: <span class="string">'E'</span>,</span><br><span class="line">replace: <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>译注：最后关于引用包含的作用域这边是一个例子，更好帮你理解 transclue</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/angularjs/" rel="tag"># angularjs</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/01/19/2020/2020-01-19-reading-keyvalue-pairs-into-dictionary-from-app-config-configsection/" rel="prev" title="c# – 从app.config configSection中读取键值对到字典">
      <i class="fa fa-chevron-left"></i> c# – 从app.config configSection中读取键值对到字典
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/04/07/2020/2020-04-07-fe-interview/" rel="next" title="前端面试题">
      前端面试题 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Gary Gong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">31</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/darktutu" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;darktutu" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gary Gong</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
